<template>
  <a-modal
    title="出库物料选择"
    width="90vw"
    :visible="visible"
    dialogClass="zero-modal"
    :zIndex="1001"
    @cancel="handleCancel">
    <a-spin :spinning="loading">
      <div class="shk-issues-choose-materials-modal">
        <div class="search-bar">
          <div class="search-form-item">
            <div class="label">批次：</div>
            <div class="content">
              <a-input placeholder="请输入..." allow-clear v-model="query.Batch" />
            </div>
          </div>
         <div class="search-form-item">
           <div class="label">巷道：</div>
           <div class="content">
             <a-select style="width: 100%" mode="multiple" placeholder="请选择..." allow-clear v-model="query.aisles">
               <a-select-option v-for="(item,index) in selectOptions.aisles" :key="'aisle-sel-'+index" :value="item">{{item}}</a-select-option>
             </a-select>
           </div>
         </div>
          <div class="search-form-item">
            <div class="label">入库时间：</div>
            <div class="content">
              <a-range-picker v-model="query.dateRange" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
            </div>
          </div>
          <div class="search-form-item">
            <div class="label">物料编号：</div>
            <div class="content">
              <a-input placeholder="请输入..." allow-clear v-model="query.MaterialNo" />
            </div>
          </div>
          <div class="search-form-item">
            <div class="label">密度：</div>
            <div class="content">
              <a-input placeholder="请输入..." allow-clear v-model="query.MaterialDensity" />
            </div>
          </div>
          <div class="bar-btns">
            <a-button type="primary" @click="onQuery">查询</a-button>
            <a-button @click="onReset" style="margin-right:0;">重置</a-button>
          </div>
        </div>
        
        <div class="result-table-view">
          <div class="more-list-head">
            <div class="more-list-padding">
              <div class="more-list-row">
                <div class="more-list-cell" v-for="(item,index) in columns" :key="'more-list-head-cell-'+index" :style="{
                  width:item.grow?'1px':(item.width?item.width:'auto'),
                  flexGrow:item.grow?item.grow:'initial',
                  flexShrink:item.grow?'initial':'0',
                  justifyContent:item.align?item.align:'center',
                  cursor:(typeof item.sort === 'number')?'pointer':'auto'
                }" @click.stop="changeTableSort(item,index)">
                  <a-checkbox v-if="item.type==='checkbox'" :indeterminate="indeterminate" :checked="checkAll"  @change="onChangeAllChecked" />
                  <template v-else>
                    {{item.name}}<up-down-sort style="margin-left:8px;" :sort="item.sort" v-if="typeof item.sort === 'number'" />
                  </template>
                </div>
              </div>
            </div>
          </div>
          <div class="more-list-body" @scroll="handleScroll" :key="listKey">
            <div class="more-list-padding">
              <div class="more-list-row" v-for="(itema,indexa) in list" :key="'more-list-row-'+indexa">
                <div class="more-list-cell" v-for="(itemb,indexb) in columns" :key="'more-list-body-cell-'+indexb" :style="{
                  width:itemb.grow?'1px':(itemb.width?itemb.width:'auto'),
                  flexGrow:itemb.grow?itemb.grow:'initial',
                  flexShrink:itemb.grow?'initial':'0',
                  justifyContent:itemb.align?itemb.align:'center'
                }">
                  <a-checkbox v-if="itemb.type==='checkbox'" :checked="itema.checked" @change="onChangeChecked($event,itema,indexa)" />
                  <template v-else-if="itemb.type==='index'">{{indexa+1}}</template>
                  <template v-else-if="itemb.type==='spec'">{{`${itema.long}*${itema.wide}*${itema.high}`}}</template>
                  <template v-else>{{itema[itemb.key]}}</template>
                </div>
              </div>
            </div>
          </div>
          
        </div>
      </div>
    </a-spin>
    
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleSubmit" :disabled="choosen.length<=0">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
import { FoamingChuKuOrderStockPage } from '@/api/modular/main/FoamingChuKuOrderManage'
import { WmsPlaceGetFAisles } from '@/api/modular/main/WmsPlaceManage'
import UpDownSort from '@/components/UpDownSort'
const defaultQuery = {
  MaterialNo:'',
  Batch:'',
  Aisle:'',
  MaterialDensity:'',
  dateRange:[],
  aisles:[],
}
const pagination = {PageNo:1,PageSize:20}
export default {
  name:'shkIssuesChooseMaterialsModal',
  emits:['update:visible','callback'],
  components:{UpDownSort},
  props:{
    visible:{
      type:Boolean,
      default:false
    }
  },
  data(){
    return {
      loading:false,
      selectOptions:{
        aisles:[]
      },
      list:[],
      query:{...defaultQuery},
      queried:{...pagination},
      columns:[
        { type:'checkbox', width:'50px' },
        { type:'index', name:'序号', width:'50px' },
        { name:'巷道', key:'aisle', width:'80px', sort:2, sortName:'AisleSort' },
        { name:'物料编号', key:'materialNo', grow:2, sort:2, sortName:'MaterialNoSort' },
        { name:'批次', key:'batch', grow:1, sort:2, sortName:'BatchSort' },
        { name:'密度', key:'materialDensity', grow:1, sort:2, sortName:'MaterialDensitySort' },
        { type:'spec', name:'尺寸', grow:2, sort:2, sortName:'LongSort' },
        { name:'库位号', key:'placeCode', width:'140px', sort:2, sortName:'PlaceCodeSort' },
        { name:'入库时间', key:'createdTime', width:'170px', sort:2, sortName:'TimeSort' }
      ],
      sortColumnIndexs:[2,3,4,5,6,7,8],  //允许排序的列序号，与columns的sort字段是否存在对应
      listKey:0,
      scrollTop:0,
      choosen:[],
      indeterminate:false,
      checkAll:false,
      hasMore:true,
      inLoading:false
    }
  },
  watch:{
    visible(newV,oldV){
      if (newV!==oldV){
        this.initShow()
        this.handleClose()
      }
    }
  },
  methods:{
    handleCancel(){
      this.$emit('update:visible',false)
    },
    initShow(){
      if (this.visible) {
        this.getAislesSelectOptions()
        this.reset()
      }
    },
    handleClose(){
      if (!this.visible) {
        this.query = {...defaultQuery}
        this.list = []
        this.choosen = []
        this.indexChoosen = []
        this.scrollTop = 0
        this.indeterminate = false
        this.checkAll = false
        this.hasMore = true
        this.inLoading = false
      }
    },
    handleSubmit(){
      this.$emit('callback',this.choosen)
      this.handleCancel()
    },
    onQuery(){
      this.newList()
    },
    onReset(){
      this.reset()
    },
    onTableChange(pagination){
      if (pagination.current!==this.queried.PageNo) {
        this.pageList(pagination.current)
      }
    },
    reset(){
      this.query = {...defaultQuery}
      this.newList()
    },
    newList(){
      let sortPorams = {}
      this.columns.forEach((columnitem)=>{
        if (typeof columnitem.sort === 'number') {
          sortPorams[columnitem.sortName] = columnitem.sort
        }
      })
      this.queried = {...this.query,...pagination,...sortPorams}
      if ((this.queried.dateRange instanceof Array) && this.queried.dateRange.length===2) {
        this.queried.SearchBeginTime = this.queried.dateRange[0] + ' 00:00:00'
        this.queried.SearchEndTime = this.queried.dateRange[1] + ' 23:59:59'
        delete this.queried.dateRange
      } else {
        delete this.queried.dateRange
        delete this.queried.SearchBeginTime
        delete this.queried.SearchEndTime
      }
      if ((this.queried.aisles instanceof Array) && this.queried.aisles.length>0) {
        this.queried.Aisle = this.queried.aisles.join(',')
        delete this.queried.aisles
      } else {
        this.queried.Aisle = ''
        delete this.queried.aisles
      }
      this.listKey = new Date().getTime()
      this.hasMore = true
      this.getList()
    },
    moreList(){
      this.queried.PageNo++
      this.getList()
    },
    getList(){
      this.loading = true
      this.inLoading = true
      FoamingChuKuOrderStockPage(this.queried).then(res=>{
        this.addList(res.data)
        this.$nextTick(()=>{
          this.inLoading = false
        })
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },
    changeTableSort(obj,index){
      if (typeof obj.sort !== 'number') return false;
      if (obj.sort===1) {
        obj.sort = 2
        this.newList()
      } else {
        this.sortColumnIndexs.forEach((item)=>{
          if (item===index) {
            if (obj.sort===0) {
              this.columns[item].sort = 1
            } else {
              this.columns[item].sort = 0
            }
            this.newList()
          } else {
            if (this.columns[item].sort!==2) {
              this.columns[item].sort = 2
              this.newList()
            }
          }
        })
      }
    },
    addList(resData){
      let arr = resData.rows || []
      if (this.queried.PageNo === 1) {
        this.list = arr
        this.checkAll = false
        this.indeterminate = false
        this.choosen = []
        this.indexChoosen = []
      }  else {
        arr.forEach((item)=>{
          this.list.push(item)
        })
        this.setAllCheckStatus()
      }
      if (this.queried.PageNo >= resData.totalPage) {
        this.hasMore = false
      }
    },
    handleScroll(e){
      let _prevTop = this.scrollTop
      this.scrollTop = e.target.scrollTop
      if (!this.hasMore || this.inLoading || this.scrollTop<=_prevTop) {
        return false
      }
      if ((e.target.scrollHeight -  e.target.clientHeight - e.target.scrollTop)<=1) {
        this.moreList()
      }
    },
    onChangeChecked(e,obj,index){
      obj.checked = e.target.checked
      this.$set(this.list,index,obj)
      this.setAllCheckStatus()
      if (obj.checked) {
        this.choosen.push(obj)
        this.indexChoosen.push(index)
      } else {
        let cIndex =  this.indexChoosen.indexOf(index);
        if (cIndex>=0){
          this.indexChoosen.splice(cIndex,1)
          this.choosen.splice(cIndex,1)
        }
      }
    },
    onChangeAllChecked(){
      if (this.checkAll) {
        this.checkAll = false
      } else {
        this.checkAll = true
      }
      this.indeterminate = false
      this.list.forEach((item)=>{
        item.checked = this.checkAll
      })
      if (this.checkAll) {
        this.choosen = [...this.list]
        this.indexChoosen = this.list.map((itemx,indexx)=>{
          return indexx
        })
      } else {
        this.choosen = []
        this.indexChoosen = []
      }
    },
    setAllCheckStatus(){
      let c = 0 , n = this.list.length;
      this.list.forEach((item)=>{
        if (item.checked) {
          c++
        }
      })
      if (c===0) {
        this.checkAll = false
        this.indeterminate = false
      } else if (c===n) {
        this.checkAll = true
        this.indeterminate = false
      } else {
        this.checkAll = false
        this.indeterminate = true
      }
    },
    getAislesSelectOptions(){
      if (this.selectOptions.aisles.length<=0) {
        WmsPlaceGetFAisles().then((d)=>{
          this.selectOptions.aisles = d.data || []
        }).catch(()=>{})
      }
    }
  }
}
</script>

<style lang="less" scoped>
.shk-issues-choose-materials-modal{
  height: 65vh;
  display: flex;
  flex-direction: column;
  .search-bar{
    display: flex;
    padding: 16px 16px 0 16px;
    flex-shrink: 0;
    flex-wrap: wrap;
    .search-form-item{
      width: 33.33%;
      flex-shrink: 0;
      display: flex;
      margin-bottom: 16px;
      &>.label{
        width: 78px;
        flex-shrink: 0;
        text-align: right;
        padding-top: 4px;
      }
      &>.content{
        width: 1px;
        flex-grow: 1;
      }
    }
    .bar-btns{
      padding-left:16px;
    }
  }
  .result-table-view{
    flex-grow: 1;
    height: 1px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: 12px;
    .more-list-head{
      flex-shrink: 0;
      .more-list-cell{
        background-color:#fafafa;
      }
    }
    .more-list-body{
      height: 1px;
      flex-grow: 1;
      overflow: auto;
    }
    .more-list-padding{
      padding: 0 16px;
    }
    .more-list-row{
      box-sizing: border-box;
      width: 100%;
      display: flex;
      border-bottom: 1px solid #e8e8e8;
      .more-list-cell{
        display: flex;
        align-items: center;
        padding: 6px 8px;
        word-break:break-all;
        word-wrap:break-word; 
      }
    }
  }
}
</style>